# == Schema Information
#
# Table name: users
#
#  id         :integer          not null, primary key
#  username   :string(255)
#  password   :string(255)
#  email      :string(255)
#  created_at :datetime
#  updated_at :datetime
#

class User < ActiveRecord::Base
  validates_presence_of :username, :password, :email
  validates_uniqueness_of :username, :email
  validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/, on: :create

  has_many :radusergroups, :dependent => :destroy, :primary_key => :username, :foreign_key => :username
  has_many :groups, :through => :radusergroups

  #has_many :radchecks, :dependent => :destroy#, :primary_key => :username, :foreign_key => :username
  has_many :radchecks, :as => :radcheckable
  has_many :radreplies, :dependent => :destroy
  has_many :radaccts, :dependent => :destroy, :primary_key => :username, :foreign_key => :username
  has_many :radpostauths, :dependent => :destroy

  after_create :set_radcheck_username
  after_save :update_radcheck_username

  protected
  def set_radcheck_username
    self.radchecks.create(
      :username => "u_#{self.username}",
      :attr => Settings.check_types['password'],
      :op => "==", 
      :value => self.password
    )
  end

  def update_radcheck_username
    if self.password_changed? 
      radcheck = self.radchecks.where(:attr => Settings.check_types['password']).first
      if radcheck
        # update_column don't callback
        radcheck.update_column(:value, self.password)
      else
        set_radcheck_username
      end
    end
  end
end
